package com.hong.utils.exchanger;

import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Auther: Administrator
 * @Date: 2018/7/22 22:47
 * @Description:
 */
public class ExchangerExample3 {
    public static void main(String[] args) {
        final Exchanger<Integer> exchanger = new Exchanger<Integer>();
        new Thread(){
            @Override
            public void run() {
                AtomicReference<Integer> values = new AtomicReference<Integer>(1);
                System.out.println("A will send object "+ values);
                try {
                    while (true){
                        values.set(exchanger.exchange(values.get()));
                        System.out.println("Thread A has Value："+values.get());
                        TimeUnit.SECONDS.sleep(3);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread(){
            @Override
            public void run() {
                AtomicReference<Integer> values = new AtomicReference<Integer>(2);
                System.out.println("A will send object "+ values);
                try {
                    while (true){
                        values.set(exchanger.exchange(values.get()));
                        System.out.println("Thread B has Value："+values.get());
                        TimeUnit.SECONDS.sleep(3);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
